﻿using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace MartinRL.ProjectEuler
{
    /// <summary>
    /// http://projecteuler.net/index.php?section=problems&id=22
    /// </summary>
    public static class Problem022
    {
        public static long FindTheTotalOfAllTheNameScores()
        {
            return File.ReadAllText(Path.Combine(Path.Combine(Environment.CurrentDirectory, "Files"), "P22_names.txt"))
                .RemoveAll("\"")
                .SplitWithCommaSeparator()
                .Select(s => new Name(s))
                .OrderBy(n => n)
                .Select((n, i) => n.GetNameValue() * (i + 1))
                .Sum();
        }
    }

    public class Name : IComparable<Name>
    {
        private readonly string value;

        public Name(string value)
        {
            this.value = value;
        }

        public string Value { get { return value; } }

        public int CompareTo(Name other)
        {
            return CultureInfo.CurrentCulture.CompareInfo.Compare(Value, other.Value, CompareOptions.Ordinal);
        }

        public int GetNameValue()
        {
            const byte asciiValueOfAt = 64; // http://en.wikipedia.org/wiki/ASCII

            return Encoding.ASCII.GetBytes(Value.ToCharArray())
                .Select(b => b - asciiValueOfAt)
                .Sum();
        }

        public override string ToString()
        {
            return Value;
        }
    }
}